package com.ddwl.common.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import java.security.MessageDigest;
import java.util.*;

/**
 * @Author hemiaojun
 * @Date 2021/6/1 16:17
 */
@Slf4j
public class SignUtil {

    /**
     * 数组
     */
    private static final String[] hexDigits = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};


    /**
     * 生成签名.
     * @param data 待签名数据
     * @return 签名
     */
    public static String generateSignature(final Map<String, String> data, List<String> noSignatureParameters){
        List<String> paramsArr = new ArrayList<>();
        for (Map.Entry<String, String> entry : data.entrySet()) {
            String key = entry.getKey();
            if (!CollectionUtils.isEmpty(noSignatureParameters)) {
                if (noSignatureParameters.contains(key)) {
                    continue;
                }
            }
            String value = entry.getValue();
            value = value.trim();
            if (value.startsWith("\"") && value.endsWith("\"") && value.length() > 1) {
                value = value.substring(1, value.length() - 1);
            }
            value = value.trim();
            if (value.equals("") || value.equals("null")) {
                continue;
            }
            paramsArr.add(value);
        }
        Collections.sort(paramsArr);
        StringJoiner sj = new StringJoiner("&");
        for (String s : paramsArr) {
            sj.add(s);
        }
        log.info("sign param [{}]",sj.toString());
        return MD5(sj.toString(),null);
    }

    /**
     * MD5加密
     *
     * @param origin
     * @param charsetname
     * @return
     */
    public static String MD5(String origin, String charsetname) {
        String resultString;
        try {
            resultString = origin;
            MessageDigest md = MessageDigest.getInstance("MD5");
            if (charsetname == null || "".equals(charsetname)) {
                resultString = byteArrayToHexString(md.digest(resultString.getBytes()));
            } else {
                resultString = byteArrayToHexString(md.digest(resultString.getBytes(charsetname)));
            }
        } catch (Exception exception) {
            resultString = null;
        }
        return resultString;
    }

    /**
     * 字符串重写
     *
     * @param b
     * @return
     */
    private static String byteArrayToHexString(byte[] b) {
        StringBuilder resultSb = new StringBuilder();
        for (int i = 0; i < b.length; i++) {
            resultSb.append(byteToHexString(b[i]));
        }
        return resultSb.toString();
    }

    /**
     * byteToHesString
     */
    private static String byteToHexString(byte b) {
        int n = b;
        if (n < 0) {
            n += 256;
        }
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigits[d1] + hexDigits[d2];
    }

}
